//
//  KHImageTool.m
//  KissHealth
//
//  Created by Mark on 2017/1/19.
//  Copyright © 2017年 Mark. All rights reserved.
//

#import "KHImageTool.h"

@implementation KHImageTool

//Base64图片 -> UIImage
+ (UIImage *)imageWithBase64String: (NSString *)imgSrc
{
    NSData *decodedImageData = [[NSData alloc]initWithBase64Encoding:imgSrc];
    UIImage *decodedImage  = [UIImage imageWithData:decodedImageData];
    
    return decodedImage;
}

//UIImage -> Base64图片
+ (NSString *)base64StingWithImage: (UIImage *) image
{
    NSData *imageData = nil;
    NSString *mimeType = nil;
    
    if ([self imageHasAlpha: image]) {
        imageData = UIImagePNGRepresentation(image);
        mimeType = @"image/png";
    } else {
        imageData = UIImageJPEGRepresentation(image, 0.2f);
        mimeType = @"image/jpeg";
    }
    
    return [imageData base64EncodedStringWithOptions:0];
}

//UIImage -> 图片 (mimeType) .jpeg
+ (NSString *)mimeTypeWithImage: (UIImage *) image
{
    NSData *imageData = nil;
    NSString *mimeType = nil;
    
    if ([self imageHasAlpha: image]) {
        imageData = UIImagePNGRepresentation(image);
        //        mimeType = @"image/png";
        mimeType = @".png";
        
    } else {
        imageData = UIImageJPEGRepresentation(image, 0.2f);
        //        mimeType = @"image/jpeg";
        mimeType = @".jpeg";
        
    }
    return mimeType;
}

//UIImage -> 图片 (mimeType) image/png
+ (NSString *)mimeTypeWithImage1: (UIImage *) image
{
    NSData *imageData = nil;
    NSString *mimeType = nil;
    
    if ([self imageHasAlpha: image]) {
        imageData = UIImagePNGRepresentation(image);
        mimeType = @"image/png";
        
    } else {
        imageData = UIImageJPEGRepresentation(image, 0.2f);
        mimeType = @"image/jpeg";
    }
    return mimeType;
}

//UIImage -> (data)
+ (NSData *)dataWithImage: (UIImage *)image
{
    NSData *imageData = nil;
    NSString *mimeType = nil;
    
    if ([self imageHasAlpha: image]) {
        imageData = UIImagePNGRepresentation(image);
        //        mimeType = @"image/png";
        mimeType = @".png";
        
    } else {
        imageData = UIImageJPEGRepresentation(image, 0.2f);
        //        mimeType = @"image/jpeg";
        mimeType = @".jpeg";
        
    }
    
    return imageData;
}


+ (BOOL)imageHasAlpha: (UIImage *) image
{
    CGImageAlphaInfo alpha = CGImageGetAlphaInfo(image.CGImage);
    return (alpha == kCGImageAlphaFirst ||
            alpha == kCGImageAlphaLast ||
            alpha == kCGImageAlphaPremultipliedFirst ||
            alpha == kCGImageAlphaPremultipliedLast);
}

@end
